package com.keyboardr.gamerater;

import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.ListFragment;
import android.view.MenuItem;
import android.widget.BaseAdapter;

public class GroupActivity extends FragmentActivity implements GroupContainer {
	public static final String GROUP_KEY = "com.keyboardr.gamerater.GROUP_KEY";
	public static final String SELECTION_KEY = "com.keyboardr.gamerater.SELECTION_KEY";
	public static final String TAG = "GroupActivity";

	private ArrayList<Group> groups;
	private Intent result;
	private int selection = -1;

	@SuppressWarnings("unchecked")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.group_list);
		setResult(-1);
		result = new Intent();
		Bundle extras = getIntent().getExtras();
		groups = (ArrayList<Group>) extras.get(GROUP_KEY);
		selection = extras.getInt(SELECTION_KEY, 0);
		result.putExtra(GROUP_KEY, groups);
		if (RaterActivity.isHolo) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	public void removeGroup(int selection) {
		groups.remove(selection);
		if (groups.size() == 0) {
			groups.add(new Group("Default", true));
		}
		groupChanged();
	}

	@Override
	public void addGroup(Group group) {
		groups.add(group);
		groupChanged();
		((ListFragment) getSupportFragmentManager().findFragmentByTag("groups"))
				.setSelection(groups.size() - 1);
	}

	private void groupChanged() {
		((BaseAdapter) ((ListFragment) getSupportFragmentManager()
				.findFragmentByTag("groups")).getListAdapter())
				.notifyDataSetInvalidated();
		result.putExtra(GROUP_KEY, groups);
		setResult(-2, result);
	}

	@Override
	public void selectGroup(int position) {
		selection = position;
		setResult(selection, result);
		finish();
	}

	@Override
	public ArrayList<Group> getGroupList() {
		return groups;
	}

	@Override
	public int getSelectedGroupPosition() {
		return selection;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
		}
		return false;
	}
}
